#!/usr/bin/python
# -*- coding: <encoding name> -*-
import time
import json

import requests

from f6zhishu.tools.db import MongoDb
from f6zhishu.tools.enc import generate_aes_key, aes_decrypt, aes_encrypt, rsa_encrypt
from f6zhishu.tools.timestamp_to_time import to_time
from f6zhishu.settings import RSA_PU_KEY

session = requests.session()


def parse_fenlie(text):
    try:
        if json.loads(text)["appPartVoList"][0]["extChoiceVos"] != None:
            return True
        else:
            return False
    except Exception as e:
        return False


class F6():
    def __init__(self):
        self.vin = None
        self.headers = {
            "authority": "data-backend.f6car.cn",
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "no-cache",
            "channel": "1",
            "content-type": "application/json;charset=UTF-8",
            "origin": "https://shop.f6car.cn",
            "pragma": "no-cache",
            "referer": "https://shop.f6car.cn/",
            "sec-ch-ua": "\"Microsoft Edge\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0",
            "x-requested-with": "XMLHttpRequest"
        }
        self.cookies = {
            "f6-data-backendSESSIONID": "58372591-0f4d-498e-b51d-10d1c4606aef",
            "un": "11861955597366751327",
            "sensorsdata2015jssdkcross": "%7B%22distinct_id%22%3A%2218c438640194eb-017232fd42cab17-26031051-2073600-18c4386401a330%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%2218c438640194eb-017232fd42cab17-26031051-2073600-18c4386401a330%22%7D",
            "erpLanguage": "zh-CN"
        }
        self.mids = None
        self.key = generate_aes_key()

        self.mongo = MongoDb()

    # 搜索部分的接口
    def search(self):
        t = {
            "vin": self.vin,
            "originalVin": "",
            "noNeedCorrectVin": "false"
        }
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/app/reqVinParse'
        data = {
            "param1": rsa_encrypt(RSA_PU_KEY, self.key),
            "param2": aes_encrypt(self.key, json.dumps(t))
        }
        data = json.dumps(data, separators=(',', ':'))
        response = session.post(url, headers=self.headers, data=data, cookies=self.cookies)
        res_data = response.json()['data']
        # 解密操作 并获取mids
        text = aes_decrypt(self.key, res_data)
        # print(text)
        js = json.loads(text)
        self.mids = js["vehicleList"][0]['mids'].split(',')
        # 对解密数据金星处理并存入数据库
        # 数据库所要的数据
        vehicleList = js["vehicleList"][0]
        # 具体字段
        brandName = vehicleList['brandName']
        vehicleSystem = vehicleList['vehicleSystem']
        year = vehicleList['year']
        exhaustVolume = vehicleList['exhaustVolume']
        transmissionDesc = vehicleList['transmissionDesc']

        # 组成全名
        name = brandName+' '+vehicleSystem+' '+year+' '+exhaustVolume+' '+transmissionDesc

        data = {'vin': self.vin, '时间': to_time(),'名称':name}
        datas = self.mongo.insert_one(data)
        if datas.get('code') == 1:
            id_ = datas.get('data').get('id')
        else:
            raise datas.get('msg')

        return id_

    # 分类部分的接口
    def fenlei(self, moduleId, id_, key, data_type):
        """
          moduleId:分类的id
          id_:存入数据库的唯一值
          key:分类名称
          data_type:大分类名称
        """
        e = {
            "channelId": 1,
            # "moduleId": moduleId,
            "moduleId": moduleId,
            "vin": self.vin,
            "mids": ','.join(map(str, self.mids))

        }
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/reqVin'
        data = {
            "param1": rsa_encrypt(RSA_PU_KEY, self.key),
            "param2": aes_encrypt(self.key, json.dumps(e))
        }
        data = json.dumps(data, separators=(',', ':'))
        response = session.post(url, headers=self.headers, cookies=self.cookies, data=data)
        time.sleep(3)
        print(response.text)
        res_data = response.json()['data']
        # 解密操作
        text = aes_decrypt(self.key, res_data)
        # 对解密数据金星处理并存入数据库

        # 传给数据库的数据列表
        db_data = []
        # 如果没有小分类就不需要再次请求
        if parse_fenlie(text):
            db_data.extend(self.fenlei_plus(text))
        else:
            # print(text)

            # 图片视频数据
            try:
                appDatumImageVos = json.loads(text)["appDatumVos"][0]["appDatumDetailVo"]["appDatumImageVos"]  # 可能存在为空
            except Exception as e:
                appDatumImageVos = None
            # 不同品牌的数据
            try:
                partCspuVoList = json.loads(text)["appPartVoList"][0]["partCspuVoList"]  # 一个数组
            except Exception as e:
                partCspuVoList = None
            res_dict = {
                "图片视频数据": appDatumImageVos,
                "不同品牌的数据": partCspuVoList
            }

            db_data.append(res_dict)

        # id_data = self.mongo.insert_convention_one(id_=id_, data={"蓄电池": db_data}, data_type=1)
        print('插入数据成功', db_data)
        id_data = self.mongo.insert_convention_one(id_=id_, data={key: db_data}, data_type=data_type)

        # 返回数据
        return db_data




    # 分类中的小分类需要再次请求
    def fenlei_plus(self, text, id=None):
        staId = \
            session.get('https://data-backend.f6car.cn/f6-data-backend/data/module/advertisementList',
                        headers=self.headers,
                        params={"moduleId": 14}, cookies=self.cookies).json()['data'][0]["staCategoryId"]
        time.sleep(3)
        data = {
            "cStr": "vPf2VAd1VgQGVIn849iDCw==",
            "channelId": 1,
            "moduleId": 14,
            "staCategoryId": staId,  #
            "useless": "De/SfBZAkGvig1YvW4w1+B7uSkQVYFHTcq5dtNTy0tjsaHKv45Dtp03MW+vJdb0X"
        }
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/queryPartListByExtChoice'
        data['cStr'] = json.loads(text)["appPartVoList"][0]["cStr"]
        # 小分类的具体数量
        length = len(json.loads(text)["appPartVoList"][0]["extChoiceVos"])

        xx_array = []
        for i in range(length):
            data['useless'] = json.loads(text)["appPartVoList"][0]["extChoiceVos"][i]["useless"]
            data_post = json.dumps(data, separators=(',', ':'))
            response = session.post(url, headers=self.headers, cookies=self.cookies, data=data_post)
            time.sleep(3)
            # print(response.text)
            # 过滤数据并存入数据库

            js = response.json()['data']
            # 图片视频数据
            try:
                appDatumImageVos = js["appDatumVos"][0]["appDatumDetailVo"]["appDatumImageVos"]  # 可能存在为空
            except Exception as e:
                appDatumImageVos = None
            # 不同品牌的数据
            partCspuVoList = js["appPartVoList"][0]["partCspuVoList"]  # 一个数组

            res_dict = {
                "图片视频数据": appDatumImageVos,
                "不同品牌的数据": partCspuVoList
            }
            xx_array.append(res_dict)
        return xx_array  # 将不同备注的分类以数组的形式返回

    # 右上角详情部分接口
    def detail(self):
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/app/vehicleDetailListToken'
        data = {
            'vin': self.vin,
            'mids': self.mids
        }
        response = session.get(url, headers=self.headers, cookies=self.cookies, params=data, )
        res_data = response.json()['data']

        # 对解密数据进行处理并存入数据库
        # print(res_data)
        vehicles = res_data["vehicles"]  # 一个数组

    def mian(self, get_dict: dict, vin, cookies=None):
        if not cookies:
            self.cookies = cookies
        self.vin = vin
        id_ = self.search()
        self.detail()
        for key, value in get_dict.items():
            for x, y in value.items():
                self.fenlei(y, id_, x, key)


if __name__ == '__main__':
    """"""
    # zidian = get_dict()
    # while True:
    #     # vin = str(input("请输入vin数据："))
    #     F6 = F6("LFV2A2156L3519836", zidian)
    #     F6.mian()


